package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.range.ip.IpRangeAggregationBuilder;

import java.net.UnknownHostException;

public class IpRangeAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        IpRangeAggregationBuilder ipRangeAggregationBuilder = AggregationBuilders.ipRange("agg").field("ip")
                .addUnboundedTo("100.0.0.5").addUnboundedFrom("100.0.0.5");
        SearchResponse searchResponse = transportClient.prepareSearch("test")
                        .setSize(0).addAggregation(ipRangeAggregationBuilder).get();
        Range range = searchResponse.getAggregations().get("agg");
        for(Range.Bucket bucket: range.getBuckets()) {
            System.out.println(bucket.getKey() + "(" + bucket.getFrom() + "-" + bucket.getTo() + "):" + bucket.getDocCount());
            //getFrom/getTo返回的是String类型，unbounded对应null
        }

        transportClient.close();
    }

}
